using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Decav.Gatsb;
using Decav.Gatsb.Data;
using Decav.Gatsb.Application;
using Decav.Data;
using Decav.Gatsb.Web;

public partial class Places : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ((IMasterPageTemplate)Master).SelectedPage = MainMenuNavigationButton.Places;

        if (!IsPostBack)
        {
            paging.CurrentPage = CurrentPage;

            if (ForUser)
                DoUserSearch();
            else
                DoGeneralSearch();
        }

        SetupMenu();
    }

    /// <summary>
    /// Gets or sets the total number of items.
    /// </summary>
    private int TotalCount
    {
        get
        {
            if (ViewState["TotalCount"] == null)
                return 1;
            else
                return (int)ViewState["TotalCount"];
        }
        set
        {
            ViewState["TotalCount"] = value;
        }
    }

    /// <summary>
    /// Gets the page to select.
    /// </summary>
    public int CurrentPage
    {
        get
        {
            if (Request.QueryString["Page"] == null || Request.QueryString["Page"].Length == 0)
                return 1;

            int i = 0;
            if (!Int32.TryParse(Request.QueryString["Page"], out i))
            {
                Response.Redirect("Places.aspx");
                return 0;
            }
            else
                return i;
        }
    }

    /// <summary>
    /// Gets the unique identifier of the user to show for.
    /// </summary>
    public Guid UserId
    {
        get
        {
            if (Request.QueryString["User"] == null || Request.QueryString["User"].Trim().Length == 0)
                return Guid.Empty;

            return new Guid(Request.QueryString["User"]);
        }
    }

    /// <summary>
    /// Gets if the places are for a user.
    /// </summary>
    protected bool ForUser
    {
        get
        {
            return UserId != Guid.Empty;
        }
    }

    private void DoUserSearch()
    {
        bool isCurrentUser = GatsbApplication.Current.UserPresent &&
            GatsbApplication.Current.CurrentUser.Id == UserId;
        User user = null;
        if (isCurrentUser)
        {
            user = GatsbApplication.Current.CurrentUser;

            pageHeader.InnerText = string.Format("Places you've been - Page {0}", CurrentPage);
            GatsbWebApplication.SetPageName(this, pageHeader.InnerText);
        }
        else
        {
            using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
                user = adapt.GetUser(UserId);

            pageHeader.InnerHtml = string.Format("Places <a href=\"{0}\">{1}</a> has been - Page {2}",
                user.Id, user.Name, CurrentPage);
            GatsbWebApplication.SetPageName(this, pageHeader.InnerText);
        }

        PaginationResult<Location> result = null;
        using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
            result = adapt.GetUserLocations(UserId, CurrentPage, PageSize);


        if (result.TotalCount == 0)
        {
            placesListDiv.Visible = false;
            noPlacesDiv.Visible = true;
            noPlacesDiv.InnerHtml = isCurrentUser ? "You have not been anywhere yet!<br/><a href=\"GettingStarted.aspx\">Read the getting started</a> guide to learn how to set your location." :
                string.Format("{0} has not been to any locations yet.", user.Name.FirstName);
        }
        else
        {
            placesListDiv.Visible = true;
            noPlacesDiv.Visible = false;
            namedPersonPlacesHref.HRef = System.String.Format("Places.aspx?user={0}", UserId);
            namedPersonPlacesHref.InnerText = string.Format("Places {0} has been", user.Name.FirstName);
            TotalCount = result.TotalCount;
            placesRepeater.DataSource = result.Items;
            placesRepeater.DataBind();

            DoPages();
        }
    }

    private void DoGeneralSearch()
    {
        pageHeader.InnerText = string.Format("All Places - Page {0}", CurrentPage);
        GatsbWebApplication.SetPageName(this, pageHeader.InnerText);

        PaginationResult<Location> result = null;
        using (IGatsbDataAdapter adapt = GatsbApplication.Current.GetDataAdapter())
            result = adapt.GetLocationsNear(null, CurrentPage - 1, PageSize);

        TotalCount = result.TotalCount;
        placesRepeater.DataSource = result.Items;
        placesRepeater.DataBind();

        DoPages();
    }

    protected virtual void FindPlaceButton_Click(object sender, EventArgs e)
    {
        string url = GatsbWebApplication.Current.CreateSearchUrl(findPlaceTextBox.Text, false, true);
        Response.Redirect(url);
    }

    private void DoPages()
    {
        paging.UrlFormat = string.Format("Places.aspx?page={0}{1}", "{0}", ForUser ?
            string.Format("&user={0}", UserId) : string.Empty);
        paging.CurrentPage = CurrentPage;
        paging.TotalCount = TotalCount;
    }

    private void SetupMenu()
    {
        if (GatsbApplication.Current.UserPresent)
            yourPlacesHref.HRef = string.Format("Places.aspx?user={0}", GatsbApplication.Current.CurrentUser.Id);
     
        namedPersonPlacesMenuItem.Visible = ForUser;
        yourPlacesMenuItem.Visible = HttpContext.Current.User.Identity.IsAuthenticated;

        if (GatsbApplication.Current.UserPresent && GatsbApplication.Current.CurrentUser.Id == UserId)
        {
            yourPlacesMenuItem.Attributes["class"] = "Selected";
            namedPersonPlacesMenuItem.Visible = false;
        }
        else if (ForUser)
        {
            namedPersonPlacesMenuItem.Attributes["class"] = "Selected";
        }
        else
        {
            allPlacesMenuItem.Attributes["class"] = "Selected";
        }
    }
}
